import CardStore from "..";
import { action } from "mobx";
import _ from "lodash";
import ModeExcel from "../ModeExcel";
import { getVerifyEntity, cubeVerifyRepeat, doSubmit,checkCardDataChange} from "../../../apis/card";
import { message, Modal } from "antd";
import window from '../../../util';
import { WeaLocaleProvider,WeaTools } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
import $ from "jquery";
const getParent = WeaTools.WindowFunc.getParent;
/**
 *
 * 卡片必填竖向滚动
 */
export const scrollTo = ($ele: any, form, callback: Function) => {
    if ($ele.length == 0) {
        setTimeout(() => {
            $ele = form.firstErrorField;
            if ($ele) {
                scrollTo($ele, form, callback);
            }
        }, 100);
        return;
    }
    /***判断是不是内联form */
    let $scroll = $('div').hasClass('cube-card-inline-wrapper') ?  $(".cube-card-wrap").closest(".cube-card-inline-wrapper"):$(".cube-card-wrap").closest(".cube-card-form-content");
    $scroll = $scroll.length == 0 ? $(".cube-card-wrap").closest(".cube-card-inline-tab-wrapper") : $scroll;
    const viewHeight = $scroll.parent().height();
    const curScrollTop = $scroll.scrollTop();
    $scroll.animate({
        scrollTop: $ele.offset().top + curScrollTop - viewHeight / 2
    }, 300, () => { callback($ele); });
    if ($scroll.length == 0) {
        callback($ele);
    }
}
/**
 *
 * 卡片必填明细表横向滚动
 */
export const scrollToX = ($ele: any, form, callback: Function) => {
    if ($ele.length == 0) {
        setTimeout(() => {
            $ele = form.firstErrorField;
            if ($ele) {
                scrollToX($ele, form, callback);
            }
        }, 100);
        return;
    }
    let $scroll = $($ele).closest(".excelDetailTable_wrap");
    const viewWidth = $scroll.width();
    const curScrollWidth = $scroll.scrollLeft();
    $scroll.animate({
        scrollLeft: $ele.offset().left - $scroll.offset().left - viewWidth / 2 + curScrollWidth
    }, 300, () => { callback() });
}

export interface VerifyErrorProps {
    errorFields: string[];
    errors: string[];
    color: string;
    operate: string;
    index: string;

    isDetailSelfRepeat: boolean;
    fields: string[];
    repeatIndex: string[];
    detailName: string;
    detail: string;
}

export default class DoSubmit {
    card: CardStore;
    constructor(card) {
        this.card = card;
    }

    execute = (pageexpandid: string, issystemflag: string, btntype?: string, isRefreshto = true, callBack?, method?: string) => {
        let isSub = true;
        if (btntype && btntype == "99") {  //保存草稿
            this.doSubmitDraft(pageexpandid, issystemflag,btntype,isRefreshto,callBack);
            return;
        }
        const promise = new Promise((resolve, reject) => {
            if (this.check_table() && this.check_form()) {
                checkCardDataChange({...this.card.params,changeDataTime:this.card.changeDataTime}).then(({errMessage='',isChange=true})=>{
                    if(!isChange){
                        isSub = false;
                        Modal.confirm({
                            title: errMessage,
                            okText: getLabel(382958, '确定'),
                            cancelText: getLabel(201, '取消'),
                            onOk: () => {
                               return;
                            },
                            onCancel: () => {
                                return;
                            }
                        });
                    }else{
                        this.verifyRepeat().then(() => {
                            resolve();
                        }).catch((e) => {
                            reject(e);
                        });
                    }
                });
            } else {
                reject();
            }
        }).then(() => {
            const submitData = () => {
                try {
                    if (_.isFunction(window.startUploadAll)) {
                        window.startUploadAll();
                    }
                    let allUploaded = false;
                    let timer = setInterval(() => {
                        allUploaded = true;
                        this.card.uploadFields.map((f: string) => {
                            if (!allUploaded) {
                                return;
                            }
                            const { isdetail, detail } = this.card.getFieldProps(f);
                            if (isdetail) {
                                if (this.card.cubeForm.has(detail)) {
                                    const detailTable = this.card.cubeForm.$(detail);
                                    detailTable.map(row => {
                                        if (!allUploaded) {
                                            return;
                                        }
                                        if (row.has(f)) {
                                            if (!row.$(f).isUpload) {
                                                allUploaded = false;
                                            }
                                        }
                                    })
                                }
                            } else {
                                if (this.card.cubeForm.has(f)) {
                                    if (!this.card.cubeForm.$(f).isUpload) {
                                        allUploaded = false;
                                    }
                                }
                            }
                        })
                        if (allUploaded) {
                            if (typeof (getParent()['slideflgfun']) == 'function') {
                                if (getParent()['slideflgfun']()) {
                                    getParent()['dosubmitfun']();
                                }
                            }
                            if(isSub){
                                this.doSubmitPost(pageexpandid, issystemflag, btntype, isRefreshto, callBack, method);
                                clearInterval(timer);
                            }
                        }
                    }, 100);
                } catch (e) {
                    if(isSub){
                        this.doSubmitPost(pageexpandid, issystemflag, btntype, isRefreshto, callBack, method);
                    }
                }
            }
            if (typeof (window.checkCustomize) == 'function') {
                try {
                    new Promise((resolve) => {
                        const a: any = window.checkCustomize(resolve);
                        if (typeof a === 'boolean') {
                            resolve(a)
                        }
                    }).then(res => {
                        if (res) {
                            submitData();
                        }
                    })
                } catch (e) {
                    return false;
                }
            } else {
                submitData();
            }
        }).catch((e) => {
            // window.console && window.console.log(e);
        })
        return promise;
    }

    ecmeExecute = () => {
        const promise = new Promise((resolve, reject) => {
            if (this.check_table() && this.check_form()) {
                this.verifyRepeat().then(() => {
                    if (typeof (window.checkCustomize) == 'function') {
                        try {
                            var flag = window.checkCustomize();
                            if (!flag) {
                                return false;
                            }
                        } catch (e) {
                            return false;
                        }
                    }
                    try {
                        if (_.isFunction(window.startUploadAll)) {
                            window.startUploadAll();
                        }
                        let allUploaded = false;
                        let timer = setInterval(() => {
                            allUploaded = true;
                            this.card.uploadFields.map((f: string) => {
                                if (!allUploaded) {
                                    return;
                                }
                                const { isdetail, detail } = this.card.getFieldProps(f);
                                if (isdetail) {
                                    if (this.card.cubeForm.has(detail)) {
                                        const detailTable = this.card.cubeForm.$(detail);
                                        detailTable.map(row => {
                                            if (!allUploaded) {
                                                return;
                                            }
                                            if (row.has(f)) {
                                                if (!row.$(f).isUpload) {
                                                    allUploaded = false;
                                                }
                                            }
                                        })
                                    }
                                } else {
                                    if (this.card.cubeForm.has(f)) {
                                        if (!this.card.cubeForm.$(f).isUpload) {
                                            allUploaded = false;
                                        }
                                    }
                                }
                            })
                            if (allUploaded) {
                                if (typeof (window.parent['slideflgfun']) == 'function') {
                                    if (window.parent['slideflgfun']()) {
                                        window.parent['dosubmitfun']();
                                    }
                                }
                                clearInterval(timer);
                                resolve();
                            }
                        }, 100);
                    } catch (e) {
                        return false;
                    }
                }).catch((e) => {
                    reject(e);
                });
            } else {
                reject();
            }
        }).then(() => {
            return this.ecmeDoSubmitPost();
        }).catch((e) => {
            (window as any).console && (window as any).console.log(e);
        })
        return promise;
    };

    getSubmitData = () => {
        const data: any = {};
        this.card.cubeForm.map(f => {
            if (f.key.startsWith('detail_')) {
                const detailExcel = this.card.modeExcel.getExcel(f.key);
                if (!detailExcel) {
                    return;
                }
                const isDrag=this.card.cubeForm.$(f.key).isDrag;
                const { detailProps } = detailExcel;
                let isHideNull = false;
                if (detailProps && detailProps.isHideNull) {
                    isHideNull = true;
                }
                if (isHideNull) {
                    if(isDrag){
                        let values=this.getDragedData(f);
                        _.set(data, f.key, values);
                    }else{
                        f.map(row => {
                            let isNull = true;
                            row.map(d => {
                                let value = d.getValue();
                                if (d.key != 'checkbox' && !!value) {
                                    isNull = false;
                                }
                            });
                            if (!isNull) {
                                _.set(data, `${f.key}.[${row.key}]`, row.values())
                            }
                        });
                    }
                } else {
                    if(isDrag){
                        let values=this.getDragedData(f);
                        _.set(data, f.key, values);
                    }else{
                        _.set(data, f.key, f.values());
                    }
                }

                const submitdtlids = f.map(row => {
                    return row.key;
                }).join(",");
                _.set(data, `submitdtlid${f.key.replace('detail_', '')}`, submitdtlids);
            } else {
                const {fieldhtmltype,fieldtype}=this.card.getFieldProps(f.path)
                if(fieldhtmltype=='3'&&fieldtype=='17'){//多人力资源特殊处理
                    const groupInfo=f.buildMultiUserGroupInfo(f.getValue(),f.valueObj);
                    const groupnum = groupInfo.groupnum;
                    for (let i = 0; i < groupnum; i++) {
                        if (`group_${i}` in groupInfo)
                            _.set(data,`${f.key}group${i}`,groupInfo[`group_${i}`]);
                    }
                    _.set(data,`${f.key}groupnum`,groupnum);
                }
                _.set(data, f.key, f.getValue());
            }
        });

        return data;
    }

    getDragedData = (f)=>{
        const detailindex=f.key.replace('detail_', '');
        let realIds= new Array();
        $("#oTable"+detailindex+" tr").each((item,e)=>{
            let rowindex=$(e).attr('data-rowindex');
            if(rowindex){
                realIds.push(parseInt(rowindex));
            }
        })
        //如果有删除行,可能会出现索引错乱
        let sortids=[...realIds];
        sortids.sort((a,b)=>{return a-b;});
        let map= new Map();
        sortids.forEach((v,index)=>{map.set(v,index)})
        for(let i=0;i<realIds.length;i++){
            realIds[i]=map.get(realIds[i]);
        }
        let datas = new Array();
        const values=f.values();
        realIds.forEach((rowindex)=>{
            if(rowindex<=values.length){
                datas.push(values[rowindex]);
            }
        });
        return datas;
    }

    /**
     * btntyoe == 3 //保存并新建
     * btntyoe == 4 //保存并复制
     * btntyoe == 5 //明细导入
     * btntype == 99 //保存草稿
     * detailid：页面扩展id
     * issystemflag  是否是系统标签
     * isRefreshto 是否跳转页面
     * callBack  回调函数
     */
    doSubmitPost = (detailid: string, issystemflag: string, btntype?: string, isRefreshto = true, callBack?: Function, method?: string) => {
        try {
            const values = this.getSubmitData();
            const { type } = this.card.params;
            const layoutid = this.card.layoutid;
            let isOreadySubmit = this.card.isOreadySubmit;
            const isFormMode = "1";
            const iscreate = this.card.base.billid ? '2' : type;
            let src = (type == 1 && !this.card.base.billid) ? "submit" : "save";
            if(method){
                src = method;
            }
            const currentLayoutId = layoutid;
            this.card.cardTab.disabled = true;
            //if(iscreate == '2'){
                if(!isOreadySubmit ){
                    return;
                }
                if(iscreate == '1'){
                     this.card.setIsOreadySubmit(false);
                }
                checkCardDataChange({...this.card.params,changeDataTime:this.card.changeDataTime,iscreate:iscreate}).then(({errMessage='',isChange=true})=>{
                    if(isChange){
                        doSubmit({
                            ...this.card.params,
                            token:this.card.token,
                            layoutid,
                            isFormMode,
                            iscreate,
                            src,
                            currentLayoutId,
                            pageexpandid: detailid,
                            JSONStr: JSON.stringify(values),
                            btntype,
                            issystemflag,
                            oldmodedatastatus: this.card.base["modedatastatus"] == 1 ? 1 : 0,
                            ...this.card.submitParam
                        }).then(({ billid,repeat,sqlresult,pageExpendResult }) => {
                            let iscontinue=this.handleResult(billid,repeat,sqlresult,pageExpendResult,this.card.params,btntype)
                            if(!iscontinue){
                                //新建完成后，后面push会添加一个key，这里删掉key，确保不会两个key导致两次请求。
                                delete this.card.params._key;
                                return;
                            }
                            let { query } = window.weaHistory.getCurrentLocation();
                            query = { ...this.card.params, ...query };
                            /**************************************外部调用保存方法，例如：合同使用建模卡片，操作之后*** */
                            
                            if (window._cubeCard && window._cubeCard.reLoad) {
                                this.card.cardTab.disabled = false;
                                if (btntype == '3') {
                                    window._cubeCard.reLoad();
                                    return;
                                }
                                window._cubeCard.reLoad(billid);
                                return;
                            }
                            /*------------------------------------------------------------------------------------*/
                            if (callBack && typeof callBack == 'function') {
                                callBack(billid);
                            }
                            if (isRefreshto) {  //需要跳转到显示页面了在设置，否则取当前的type
                                query.type = '0';  //type =0 显示 1 新建
                            }else{
                                query.isSaveCallback = true;//监控是不是保存之后的页面刷新，不跳转页面，判断重复请求问
                            }
                            query.billid = billid;
                            if (btntype == '3') {
                                query.type = '1';
                                delete query.billid;
                                delete query.copyid;
                            } else if (btntype == '4') {
                                query.copyid = billid;
                                query.type = '1';
                                delete query.billid;
                            } else if (btntype == '5') {
                                query.type = '1';
                            }
                            query.t = new Date().getTime();
                            delete query._key; //新建完成后，后面push会添加一个key，这里删掉key，确保不会两个key导致两次请求。
                            if (btntype != '3' && btntype != '4' && btntype != '5' && btntype != '99') {
                                delete query.layoutid;
                            }
                            let otherQuery:any=[];
                            if(btntype != '3'){
                                _.mapKeys(query, (value, key) => {if(!key.startsWith('field'))otherQuery[key]=value;return 0;});//去除掉field开头的参数，避免新增链接上的参数带到显示页面
                            }else{
                                _.mapKeys(query, (value, key) => {otherQuery[key]=value;return 0;});//去除掉field开头的参数，避免新增链接上的参数带到显示页面
                            }
                            const queryStr = _.keys(_.mapKeys(otherQuery, (value, key) => {
                                return `${key}=${value}`;
                            })).join("&");
                            if(query.type == '0'){
                                query={...otherQuery};
                            }

                            if (btntype == '5') {
                                this.card.init(query, this.card.showDetailImport);
                            } else if (this.card.params && this.card.params.istree) {  //处理树的情况下，是否刷新左侧树，禁止路由跳转
                                this.card.init(query);
                                if (this.card.params.isRefreshTree == '1') {
                                    (window as any).refreshTree(this.card.params.customTreeDataId);
                                }
                            } else if (this.card.params && this.card.params.isInnerCard) {  //处理内嵌卡片的情况，禁止路由跳转
                                const cardParams = this.card.getQuery(this.card.targetHref);
                                cardParams.type = '0';  //type =0 显示 1 新建
                                cardParams.billid = billid;
                                if (btntype == '3') {
                                    cardParams.type = '1';
                                    delete cardParams.billid;
                                } else if (btntype == '4') {
                                    cardParams.copyid = billid;
                                    cardParams.type = '1';
                                    delete cardParams.billid;
                                } else if (btntype == '5') {
                                    cardParams.type = '1';
                                }
                                cardParams.t = new Date().getTime();
                                delete cardParams._key;
                                this.card.innerCardInit(cardParams);
                            } else if (!isRefreshto) {
                                this.card.init(query);
                            } else {
                                window.weaHistory.push({ pathname: `/main/cube/card?${queryStr}` });
                            }
                            try {
                                //--------------------------------------是否看板，看板相关处理
                                const { boardid, boardgroup, boardcustomid, viewfrom } = this.card.params;
                                if (boardid && boardgroup && boardcustomid) {
                                    if(top.window['current_boardStore']){
                                        top.window['current_boardStore'].cardSaveFun(billid, iscreate, boardid, boardgroup, boardcustomid,btntype);
                                    }else if(window.opener && window.opener.cubeStore){
                                        window.opener.cubeStore.boardStore.doSearch();
                                    }
                                }else if(viewfrom == 'fromboarditem' && window.opener && window.opener.cubeStore){
                                    window.opener.cubeStore.boardStore.doSearch();
                                }else{
                                    //--------------打开的列表数据回调刷新页面-----
                                    this.card.cardTab.disabled = false;
                                    if(window.opener){
                                        const { _table,cubeStore } = window.opener;
                                        if (_table && _table.reLoad) {
                                            let isTreeList = cubeStore && cubeStore.Search.dataShowtype === 'treeType' && cubeStore.Search.changeSearch == '1';// 分组的组合转换，单独判断
                                            if(isTreeList && cubeStore.Search.customId){
                                                cubeStore.Search.refresh();
                                            }else{
                                                _table.reLoad();
                                            }
                                        }else if(cubeStore && cubeStore.Search.customId){
                                            cubeStore.Search.refresh();
                                        }
                                    }
                                }
                            } catch (e) {
                            }
                        });
                    }else{
                        Modal.confirm({
                            title: errMessage,
                            okText: getLabel(382958, '确定'),
                            cancelText: getLabel(201, '取消'),
                            onOk: () => {
                               //return;
                            },
                            onCancel: () => {
                                //return;
                            }
                        });
                    }
                });
            // }else{
            //     if(!isOreadySubmit ){
            //         return;
            //     }
            //     if(iscreate == '1'){
            //          this.card.setIsOreadySubmit(false);
            //     }
            //     doSubmit({
            //         ...this.card.params,
            //         token:this.card.token,
            //         layoutid,
            //         isFormMode,
            //         iscreate,
            //         src,
            //         currentLayoutId,
            //         pageexpandid: detailid,
            //         JSONStr: JSON.stringify(values),
            //         btntype,
            //         issystemflag,
            //         oldmodedatastatus: this.card.base["modedatastatus"] == 1 ? 1 : 0
            //     }).then(({ billid,repeat,sqlresult,pageExpendResult }) => {
            //         let iscontinue=this.handleResult(billid,repeat,sqlresult,pageExpendResult,this.card.params,btntype)
            //         if(!iscontinue){
            //             //新建完成后，后面push会添加一个key，这里删掉key，确保不会两个key导致两次请求。
            //             delete this.card.params._key
            //             return;
            //         }
            //         let { query } = window.weaHistory.getCurrentLocation();
            //         query = { ...this.card.params, ...query };
            //         /**************************************外部调用保存方法，例如：合同使用建模卡片，操作之后*** */
            //         if (window._cubeCard && window._cubeCard.reLoad) {
            //             this.card.cardTab.disabled = false;
            //             if (btntype == '3') {
            //                 window._cubeCard.reLoad();
            //                 return;
            //             }
            //             window._cubeCard.reLoad(billid);
            //             return;
            //         }
            //         /*------------------------------------------------------------------------------------*/
            //         if (callBack && typeof callBack == 'function') {
            //             callBack(billid);
            //         }
            //         if (isRefreshto) {  //需要跳转到显示页面了在设置，否则取当前的type
            //             query.type = '0';  //type =0 显示 1 新建
            //         }else{
            //             query.isSaveCallback = true;//监控是不是保存之后的页面刷新，不跳转页面，判断重复请求问
            //         }
            //         query.billid = billid;
            //         if (btntype == '3') {
            //             query.type = '1';
            //             delete query.billid;
            //             delete query.copyid;
            //         } else if (btntype == '4') {
            //             query.copyid = billid;
            //             query.type = '1';
            //             delete query.billid;
            //         } else if (btntype == '5') {
            //             query.type = '1';
            //         }
            //         query.t = new Date().getTime();
            //         delete query._key; //新建完成后，后面push会添加一个key，这里删掉key，确保不会两个key导致两次请求。
            //         if (btntype != '3' && btntype != '4' && btntype != '5' && btntype != '99') {
            //             delete query.layoutid;
            //         }
            //         let otherQuery:any=[];
            //         if(btntype != '3'){
            //             _.mapKeys(query, (value, key) => {if(!key.startsWith('field'))otherQuery[key]=value;return 0;});//去除掉field开头的参数，避免新增链接上的参数带到显示页面
            //         }else{
            //             _.mapKeys(query, (value, key) => {otherQuery[key]=value;return 0;});//去除掉field开头的参数，避免新增链接上的参数带到显示页面
            //         }
            //         const queryStr = _.keys(_.mapKeys(otherQuery, (value, key) => {
            //             return `${key}=${value}`;
            //         })).join("&");
            //         if(query.type == '0'){
            //             query={...otherQuery};
            //         }


            //         if (btntype == '5') {
            //             this.card.init(query, this.card.showDetailImport);
            //         } else if (this.card.params && this.card.params.istree) {  //处理树的情况下，是否刷新左侧树，禁止路由跳转
            //             this.card.init(query);
            //             if (this.card.params.isRefreshTree == '1') {
            //                 (window as any).refreshTree(this.card.params.customTreeDataId);
            //             }
            //         } else if (this.card.params && this.card.params.isInnerCard) {  //处理内嵌卡片的情况，禁止路由跳转
            //             const cardParams = this.card.getQuery(this.card.targetHref);
            //             cardParams.type = '0';  //type =0 显示 1 新建
            //             cardParams.billid = billid;
            //             if (btntype == '3') {
            //                 cardParams.type = '1';
            //                 delete cardParams.billid;
            //             } else if (btntype == '4') {
            //                 cardParams.copyid = billid;
            //                 cardParams.type = '1';
            //                 delete cardParams.billid;
            //             } else if (btntype == '5') {
            //                 cardParams.type = '1';
            //             }
            //             cardParams.t = new Date().getTime();
            //             delete cardParams._key;
            //             this.card.innerCardInit(cardParams);
            //         } else if (!isRefreshto) {
            //             this.card.init(query);
            //         } else {
            //             window.weaHistory.push({ pathname: `/main/cube/card?${queryStr}` });
            //         }

            //         //--------------打开的列表数据回调刷新页面-----
            //         try {
            //             this.card.cardTab.disabled = false;
            //             if (window.opener && window.opener._table && window.opener._table.reLoad) {
            //                 window.opener._table.reLoad();
            //             }else if(window.opener && window.opener.cubeStore){
            //                 window.opener.cubeStore.Search.refresh();
            //             }
            //         } catch (e) {
            //         }
            //         //--------------------------------------------------------
            //         //--------------------------------------是否看板，看板相关处理
            //         try {
            //             const { boardid, boardgroup, boardcustomid } = this.card.params;
            //             if (boardid && boardgroup && boardcustomid) {
            //                 top.window['current_boardStore'].cardSaveFun(billid, iscreate, boardid, boardgroup, boardcustomid);
            //             }
            //         } catch (e) {
            //         }
            //         //----------------------------------------是否看板，看板相关处理
            //     });
            // }

        } catch (error) {

      }
    }

    handleResult = (billid,repeat,sqlresult,pageExpendResult,params?,btntype?) =>{
        if(repeat&&(repeat=="true"||repeat==true)){
            message.error(getLabel('511158','禁止重复提交表单'));
            return false;
        }
        if(sqlresult&&sqlresult=="false"){
            Modal.error({
                content:getLabel('511621','sql执行错误,请联系管理员查看后台日志')
            })
            return false;
        }
        if(billid==undefined){
            Modal.error({
                content:getLabel('512662','保存数据出错!billid为空')
            })
            return false;
        }
        if(pageExpendResult){
            let obj=JSON.parse(pageExpendResult);
            let _this = this;
            if(obj.flag=="false"){
                Modal.error({
                    content:<div dangerouslySetInnerHTML={{__html:obj.errmsg}}></div>,
                    onOk() {
                        _this.jumpPath(billid,params,btntype);
                    },
                    onCancel(){
                        _this.jumpPath(billid,params,btntype);
                    }
                })
				 return false;
            }else if(obj.flag=="true"&&obj.interfacetype&&obj.interfacetype=='6'&&obj.callbackFun){
                const callbackFun=obj.callbackFun;
                const esbdata=obj.esbdata;
                eval(callbackFun + "("+esbdata+")");
            }
        }
        return true;
    }

    jumpPath = (billid,params,btntype) => {
        let { query } = window.weaHistory.getCurrentLocation();
        query = { ...params, ...query };
        query.billid = billid;
        delete query.layoutid;
        query.type = '0';
        if (btntype == '3') {
            query.type = '1';
            delete query.billid;
            delete query.copyid;
        } else if (btntype == '4') {
            query.copyid = billid;
            query.type = '1';
            delete query.billid;
        } else if (btntype == '5') {
            query.type = '1';
        }
        let otherQuery:any=[];
        if(btntype != '3'){
            _.mapKeys(query, (value, key) => {if(!key.startsWith('field'))otherQuery[key]=value;return 0;});//去除掉field开头的参数，避免新增链接上的参数带到显示页面
        }else{
            _.mapKeys(query, (value, key) => {otherQuery[key]=value;return 0;});//去除掉field开头的参数，避免新增链接上的参数带到显示页面
        }
        const queryStr = _.keys(_.mapKeys(otherQuery, (value, key) => {
            return `${key}=${value}`;
        })).join("&");
        if(query.type == '0'){
            query={...otherQuery};
        }
        window.weaHistory.push({ pathname: `/main/cube/card?${queryStr}` });
    }

    ecmeDoSubmitPost = () => {
        try {
            const values = this.getSubmitData();
            const result = this.convertFields(values);
            this.card.cardTab.disabled = true;
            const pickCardParams = _.pick(this.card.params, ['appid', 'feaid', 'isecme']);
            const newParams: any = {
                ...pickCardParams,
                JSONStr: result,
            };
            return Promise.resolve(newParams)
        } catch (error) {

        }
    }
    /*  转换建模字段到模块字段
    *   values = {detail_1: Array(2), field-57099: "1", field-57088: "", …}
    *   return :{
    *       mainTable:{ tablename(主表或者扩展表表名):{ fieldname:"14:55",fieldname:"", …} },
    *       detaiTable:{ tablename（明细表名）:[{fieldname:"14:55",fieldname:"", …},{fieldname:"14:55",fieldname:"", …}] }
    *   }
    */
    convertFields = (values) => {
        let mainTable: any = {};
        let detailTable: any = {};
        let exmainTable: any = {};
        let exdetailTable: any = {};
        const _allFields = this.card.allFields;

        for(let key  in values){
            if(key.startsWith('field')){
                let tablename = '';
                for (let _key  in _allFields){
                    if(key == _key){
                        let issystem = _allFields[_key].issystem;
                        if(issystem == 4){
                            let tableid = _allFields[_key].tableid;
                            let extable = _.get(exmainTable,tableid);
                            if( extable == undefined){
                                extable = {};
                            }
                            _.set(extable,_key,  values[key]);
                            _.set(exmainTable,tableid,extable);
                        }else{
                            tablename = _allFields[_key].tablename;
                            let table = _.get(mainTable,tablename);
                            if( table == undefined){
                                table = {};
                            }
                            _.set(table, _allFields[_key].fieldname,  values[key]);
                            _.set(mainTable,tablename,table)
                        }
                    }
                }
            }else if(key.startsWith('detail_')){
                let dttablename = '';
                let detailTableList:any = [];
                let dttableid = '';
                let exdetailTableList:any = [];
                var dt = values[key];
                dt.forEach(function (_dtvalues,index) {
                    let dtTable = {};
                    let exdtTable = {};
                    for(let dtkey in _dtvalues){
                        if(dtkey.startsWith('field')){
                            for (let _dtkey  in _allFields){
                                 if(dtkey == _dtkey){
                                    let issystem =_allFields[_dtkey].issystem;
                                    if(issystem == 4){
                                        _.set(exdtTable, _dtkey,  _dtvalues[dtkey]);
                                        dttableid = _allFields[_dtkey].tableid;
                                    }else{
                                        _.set(dtTable, _allFields[_dtkey].fieldname,  _dtvalues[dtkey]);
                                        dttablename = _allFields[_dtkey].tablename;
                                    }

                                }
                            }
                        }else if(dtkey == 'dtl_id'){
                            _.set(dtTable,'id',  _dtvalues[dtkey]);
                            _.set(exdtTable,'id',  _dtvalues[dtkey]);
                        }
                    }
                    detailTableList.push(dtTable);
                    exdetailTableList.push(exdtTable);
                });
                _.set(detailTable, dttablename , detailTableList);
                _.set(exdetailTable, dttableid , exdetailTableList);
            }
      }
    let result: any = {
        'mainTable':mainTable,
        'detailTable': detailTable,
        'extendDatas': {
            'exmainTable':exmainTable,
            'exdetailTable': exdetailTable,
        }
    };
    return result;
    }

    @action
    setColor = (colors: any, form = this.card.cubeForm) => {
        if(_.isEmpty(colors)) return;
        _.each(colors, (color: string | any[], field: string) => {
            if(color){
                if (_.isString(color)) {
                    form.$(field).color = color;
                } else {
                    this.setColor(color, form.$(field));
                }
            }
        })
    }
    @action
    clearColor = (colors: any = [], form = this.card.cubeForm) => {
        if(_.isEmpty(colors)) return;
        _.each(colors, (color, field: string) => {
            if(color){
                if (_.isString(color)) {
                    form.$(field).color = undefined;
                } else {
                    this.clearColor(color, form.$(field));
                }
            }
        })
    }

    @action
    clearAllColor = () => {
        this.card.cubeForm.map(field => {
            field.color = undefined;
            field.map(row => {
                row.map(f => {
                    f.color = undefined;
                })
            })
        })
    }

    @action  //重复验证
    verifyRepeat = (bool = true,v_fields=[],v_fieldinfos =[]) => {
        this.clearAllColor();
        return new Promise((resolve, reject) => {
            if(bool){
                getVerifyEntity(this.card.params).then(({ status, errorCode, error, fields,fieldinfos }) => {
                    if (status != '1') {
                        message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
                        reject();
                        return;
                    }
                    if (fields && _.isArray(fields)) {
                        this.handleVerifyRepeat(fields,fieldinfos,resolve,reject);
                    } else {
                        resolve();
                    }
                })
            }else{
                this.handleVerifyRepeat(v_fields,v_fieldinfos,resolve,reject);
            }
        })
    }

    //重复验证数据处理
    @action
    handleVerifyRepeat = (fields,fieldinfos,resolve,reject)=>{
        if (fields && _.isArray(fields)) {
            let values: any = {};
            fields.map(field => {
                const { isdetail, detail } = this.card.getFieldProps(field);
                if (isdetail) {
                    this.card.cubeForm.$(detail).map((d, index) => {
                        if ( d.has(field)) {
                            _.set(values, `${detail}.[${index}].${field}`, d.$(field).getValue());
                            _.set(values, `${detail}.[${index}].dtl_id`, d.$('dtl_id').getValue());
                            _.set(values, `${detail}.[${index}].index`, index);
                        }
                    });
                } else {
                    if (this.card.cubeForm.has(field)) {
                        const value = this.card.cubeForm.$(field).getValue();
                        _.set(values, field, value);
                    }else{//设置了重复验证,但是卡片页面没有该字段
                        fieldinfos&&fieldinfos.map((info)=>{
                            if(info.fieldid==field){
                                if(info.isdetail){
                                    this.card.cubeForm.$(info.detail).map((d, index) => {
                                        _.set(values, `${info.detail}.[${index}].${field}`,"");
                                        _.set(values, `${info.detail}.[${index}].dtl_id`, "");
                                        _.set(values, `${info.detail}.[${index}].index`, index);
                                    });
                                }else{
                                    _.set(values, field, '');
                                }
                            }
                        })
                    }
                }
            });

            cubeVerifyRepeat({
                ...this.card.params,
                verifys: JSON.stringify(values)
            }).then(({ status, errorCode, error, verifyErrors }) => {
                if (status != '1') {
                    message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
                    reject();
                    return;
                }
                let confirmsStr = '';
                let confirmsIndex = 1;
                let confirmsColor: any = {};
                let breaksStr = '';
                let breaksIndex = 1;
                let breaksColor: any = {};
                let repeatFields: any = [];
                if (verifyErrors && _.isArray(verifyErrors)) {
                    verifyErrors.map((verifyError: VerifyErrorProps) => {
                        const { color, operate, errors, index, errorFields, isDetailSelfRepeat, fields, repeatIndex, detailName } = verifyError;
                        if (isDetailSelfRepeat) {
                            if (operate == '0') {  //operate == '0'禁止提交,operate == '1'	仅提醒不做处理
                                breaksStr += (breaksIndex++) + "、" + detailName + getLabel(15323, "第") + repeatIndex.map(d => d + 1).join(",") + getLabel(18620, "行") + getLabel(18082, "重复") + '.<br />';
                                fields.map(f => {
                                    const { isdetail, detail } = this.card.getFieldProps(f);
                                    if (isdetail) { //明细表
                                        if (this.card.cubeForm.has(detail)) {
                                            this.card.cubeForm.$(detail).map((row, _index) => {
                                                if (repeatIndex.indexOf(_index) > -1 && row.has(f)) {
                                                    _.set(breaksColor, `[${detail}.${row.key}.${f}]`, color);
                                                }
                                            })
                                        }
                                    } else {
                                        if (this.card.cubeForm.has(f)) {
                                            _.set(breaksColor, f, color);
                                        }
                                    }
                                });
                            } else {
                                confirmsStr += confirmsIndex + "、" + detailName + getLabel(15323, "第") + repeatIndex.map(d => d + 1).join(",") + getLabel(18620, "行") + getLabel(18082, "重复") + '.<br />';
                                confirmsIndex++;
                                fields.map(f => {
                                    const { isdetail, detail } = this.card.getFieldProps(f);
                                    if (isdetail) { //明细表
                                        if (this.card.cubeForm.has(detail)) {
                                            this.card.cubeForm.$(detail).map((row, _index) => {
                                                if (repeatIndex.indexOf(_index) > -1 && row.has(f)) {
                                                    _.set(confirmsColor, `[${detail}.${row.key}.${f}]`, color);
                                                }
                                            })
                                        }
                                    } else {
                                        if (this.card.cubeForm.has(f)) {
                                            _.set(confirmsColor, f, color);
                                        }
                                    }
                                });
                            }
                        } else {
                            if (operate == '0') {
                                repeatFields.push(verifyError);
                                breaksStr += (breaksIndex++) + "、" + (errors.length > 1 ? getLabel('83735', "组合") + getLabel('84110', "验证") : '') + errors.join(",") + getLabel('383704', "已重复") + '.<br />';
                                errorFields.map(f => {
                                    const { isdetail, detail } = this.card.getFieldProps(f);
                                    if (isdetail) {
                                        if (this.card.cubeForm.has(detail)) {
                                            this.card.cubeForm.$(detail).map((row, _index) => {
                                                if (_index == index && row.has(f)) {
                                                    _.set(breaksColor, `[${detail}.${row.key}.${f}]`, color);
                                                }
                                            })
                                        }
                                    } else {
                                        if (this.card.cubeForm.has(f)) {
                                            _.set(breaksColor, f, color);
                                        }
                                    }
                                });
                            } else {
                                repeatFields.push(verifyError);
                                confirmsStr += confirmsIndex + "、" + (errors.length > 1 ? getLabel('83735', "组合") + getLabel('84110', "验证") : '') + errors.join(",") + getLabel('383704', "已重复") + '.<br />';
                                confirmsIndex++;
                                errorFields.map(f => {
                                    const { isdetail, detail } = this.card.getFieldProps(f);
                                    if (isdetail) {
                                        if (this.card.cubeForm.has(detail)) {
                                            this.card.cubeForm.$(detail).map((row, _index) => {
                                                if (_index == index && row.has(f)) {
                                                    _.set(confirmsColor, `[${detail}.${row.key}.${f}]`, color);
                                                }
                                            })
                                        }
                                    } else {
                                        if (this.card.cubeForm.has(f)) {
                                            _.set(confirmsColor, f, color);
                                        }
                                    }
                                });
                            }
                        }
                        //breaksIndex++;
                    });
                    if (confirmsStr) {
                        this.setColor(confirmsColor);
                        Modal.confirm({
                            width: 500,
                            content: (
                                <div style={{ maxHeight: 600, overflowY: 'auto' }}>
                                    <div>{getLabel('383707', "您录入的数据不满足以下验证:")}</div>
                                    <div dangerouslySetInnerHTML={{ __html: confirmsStr }}/>
                                    <div> {getLabel(15382, '是否继续？')}</div>
                                </div>
                            ),
                            okText: getLabel(1256, "继续"),
                            cancelText: getLabel(201, "取消"),
                            title: getLabel(15172, '系统提示'),
                            onOk: () => {
                                this.clearColor(confirmsColor);
                                if (breaksStr) {
                                    this.setColor(breaksColor);
                                    Modal.error({
                                        width: 500,
                                        content: (
                                            <div style={{ maxHeight: 600, overflowY: 'auto' }}>
                                                <div>{getLabel('383707', "您录入的数据不满足以下验证:")}</div>
                                                <div dangerouslySetInnerHTML={{ __html: breaksStr }}/>
                                                <div> {getLabel('383708', "请重新录入")}！</div>
                                            </div>
                                        ),
                                        title: getLabel(15172, '系统提示'),
                                    });
                                    reject();
                                } else {
                                    resolve();
                                }
                            },
                            onCancel: () => {
                                reject();
                            }
                        });
                    } else if (breaksStr) {
                        //明细表开启了分页
                        this.repeatFieldsPosition(repeatFields);
                        this.setColor(breaksColor);
                        Modal.error({
                            width: 500,
                            content: (
                                <div style={{ maxHeight: 600, overflowY: 'auto' }}>
                                    <div>{getLabel('383707', "您录入的数据不满足以下验证:")}</div>
                                    <div dangerouslySetInnerHTML={{ __html: breaksStr }}/>
                                    <div> {getLabel('383708', "请重新录入")}！</div>
                                </div>
                            ),
                            title: getLabel(15172, '系统提示'),
                        });
                        reject();
                    } else {
                        resolve();
                    }
                } else {
                    resolve();
                }
            });
        } 
    }

    // @action
    // getFirstMainFied=()=>{
    //     let field:string = "";
    //     _.forEach(this.card.allFields,(v,key)=>{
    //         if(!v.isdetail){
    //             field = key;
    //             return;
    //         }
    //     })
    //     return field;
    // }

    @action
    check_form = (): boolean => {
        // const fistFields = this.getFirstMainFied();
        this.card.cubeForm.validate();
        this.card.cubeForm.showErrors();
        const firstErrorField = this.card.cubeForm.firstErrorField;
        if (firstErrorField) {
            /**
             * 此处处理明细表必填校验定位问题，页面跳转到当前第一个未填的数据所在的分页
             */
            const nullFieldObj = this.getDetailNullPlace();
            const path = nullFieldObj.path;
            if (path) {
                const [detail, index] = path.split('.')
                const fieldDetail = this.card.cubeForm.$(detail);
                const pageSize = Number(fieldDetail.pageSize);
                const total = fieldDetail.values().length;
                const pageTotal = Math.ceil(total / pageSize);
                for (let i = 1; i <= pageTotal; i++) {
                    if (index >= pageSize * (i - 1) && index < pageSize * i) {
                        fieldDetail.pageNum = i;
                    }
                }
            }
            scrollTo(firstErrorField, this.card.cubeForm, ($ele) => {
                const firstErrorFieldId = $ele.attr('data-fieldmark');
                const [field, index] = firstErrorFieldId.split("_");
                const { isdetail, detail } = this.card.getFieldProps(field);
                let errorField;
                if (isdetail) {
                    errorField = this.card.cubeForm.$(`${detail}.${index}.${field}`);
                    scrollToX(firstErrorField, this.card.cubeForm, () => {
                        errorField.tips = {
                            visible: true,
                            msg: errorField.errors()
                        };
                    });
                } else {
                    errorField = this.card.cubeForm.$(field);
                    errorField.tips = {
                        visible: true,
                        msg: errorField.errors()
                    };
                }
                setTimeout(() => {
                    errorField.tips = {
                        visible: false,
                        msg: ''
                    };
                }, 1500);
            });
        }
        return this.card.cubeForm.isValid;
    }
    @action
    check_table = (): boolean => {
        let rt = true;
        _.each(this.card.modeExcel.details, (detialExcel: ModeExcel, detail: string) => {
            if (detail.startsWith("detail_")) {
                if (detialExcel.detailProps.isNeed) {
                    if (this.card.cubeForm.$(detail).values().length < 1) {
                        rt = false;
                        scrollTo($(`#${detail.replace('detail_', 'oTable')}`), this.card.cubeForm, () => {
                            detialExcel.error = {
                                visible: true,
                                msg: getLabel('383709', "未新增数据") + "needAdd"
                            }
                            setTimeout(() => {
                                detialExcel.error = { visible: false, msg: getLabel('383709', "未新增数据") + "needAdd" }
                            }, 1000)
                        });

                    }
                }
            }
        });
        return rt;
    }

    doSubmitDraft = (pageexpandid: string, issystemflag: string, btntype?: string, isRefreshto = true,callBack?:Function) => {
        try {
            if (_.isFunction(window.startUploadAll)) {
                window.startUploadAll();
            }
            let allUploaded = false;
            let timer = setInterval(() => {
                allUploaded = true;
                this.card.uploadFields.map((f: string) => {
                    if (!allUploaded) {
                        return;
                    }
                    const { isdetail, detail } = this.card.getFieldProps(f);
                    if (isdetail) {
                        if (this.card.cubeForm.has(detail)) {
                            const detailTable = this.card.cubeForm.$(detail);
                            detailTable.map(row => {
                                if (!allUploaded) {
                                    return;
                                }
                                if (row.has(f)) {
                                    if (!row.$(f).isUpload) {
                                        allUploaded = false;
                                    }
                                }
                            })
                        }
                    } else {
                        if (this.card.cubeForm.has(f)) {
                            if (!this.card.cubeForm.$(f).isUpload) {
                                allUploaded = false;
                            }
                        }
                    }
                })
                if (allUploaded) {
                    if (typeof (window.parent['slideflgfun']) == 'function') {
                        if (window.parent['slideflgfun']()) {
                            window.parent['dosubmitfun']();
                        }
                    }
                    this.doSubmitDraftPost(pageexpandid, issystemflag,callBack);
                    clearInterval(timer);
                }
            }, 100);
        } catch (e) {
            this.doSubmitDraftPost(pageexpandid, issystemflag,callBack);
        }
    }

    doSubmitDraftPost = (detailid: string, issystemflag: string,callBack?:Function) => {
        const values = this.getSubmitData();
        const { type } = this.card.params;
        const layoutid = this.card.layoutid;
        const isFormMode = "1";
        const iscreate = this.card.base.billid ? '2' : type;
        const src = (type == 1 && !this.card.base.billid) ? "submit" : "save";
        const currentLayoutId = layoutid;
        this.card.cardTab.disabled = true;
        doSubmit({
            ...this.card.params,
            token:this.card.token,
            layoutid,
            isFormMode,
            iscreate,
            src,
            currentLayoutId,
            pageexpandid: detailid,
            JSONStr: JSON.stringify(values),
            issystemflag,
            modedatastatus: 1,
            ...this.card.submitParam
        }).then(({ billid,pageExpendResult }) => {
            if(pageExpendResult){
                let obj=JSON.parse(pageExpendResult);
                if(obj.flag=="false"){
                    Modal.error({
                        content:obj.errmsg
                    })
                    return;
                }
            }
            let { query } = window.weaHistory.getCurrentLocation();
            query = { ...this.card.params, ...query };
            query.type = '0';  //type =0 显示 1 新建
            query.billid = billid;
            query.t = new Date().getTime();
            delete query._key; //新建完成后，后面push会添加一个key，这里删掉key，确保不会两个key导致两次请求。
            const queryStr = _.keys(_.mapKeys(query, (value, key) => {
                return `${key}=${value}`;
            })).join("&");
            if (callBack && typeof callBack == 'function') {
                callBack(billid);
            }
            if (this.card.params && this.card.params.istree) {  //处理树的情况下，是否刷新左侧树，禁止路由跳转
                this.card.init(query);
                if (this.card.params.isRefreshTree == '1') {
                    (window as any).refreshTree(this.card.params.customTreeDataId);
                }
            } else {
                window.weaHistory.push({ pathname: `/main/cube/card?${queryStr}` });
            }
            
            try {
                //--------------------------------------是否看板，看板相关处理
                const { boardid, boardgroup, boardcustomid,viewfrom } = this.card.params;
                if (boardid && boardgroup && boardcustomid) {
                    if(top.window['current_boardStore']){
                        top.window['current_boardStore'].cardSaveFun(billid, iscreate, boardid, boardgroup, boardcustomid);
                    }else if(window.opener && window.opener.cubeStore){
                        window.opener.cubeStore.boardStore.doSearch();
                    }
                }else if(viewfrom == 'fromboarditem' && window.opener && window.opener.cubeStore){
                    window.opener.cubeStore.boardStore.doSearch();
                }else{
                    //--------------打开的列表数据回调刷新页面-----
                    this.card.cardTab.disabled = false;
                    if(window.opener){
                        const { _table,cubeStore } = window.opener;
                        if (_table && _table.reLoad) {
                            let isTreeList = cubeStore && cubeStore.Search.dataShowtype === 'treeType' && cubeStore.Search.changeSearch == '1';// 分组的组合转换，单独判断
                            if(isTreeList && cubeStore.Search.customId){
                                cubeStore.Search.refresh();
                            }else{
                                _table.reLoad();
                            }
                        }else if(cubeStore && cubeStore.Search.customId){
                            cubeStore.Search.refresh();
                        }
                    }
                }
            } catch (e) {
            }
            //----------------------------------------是否看板，看板相关处理
        });
    }
    @action
    getDetailNullPlace = () => {
        let nullField: any = {};
        this.card.cubeForm.map(d => d.key.startsWith('detail_') && d.map(a => a.map(b => {
            if (!b.isValid && _.isEmpty(nullField)) {
                nullField = b;
                return;
            }
            ;
            return b.isValid
        })));
        return { path: nullField.path || "", label: nullField.label || "" }
    }

    /**
     * 明细表分页重复验证定位
     */
    @action
    repeatFieldsPosition = (fields: any = []) => {
        let detailObj: any = {};
        fields.map(field => {
            const f = field.errorFields[0];
            const { isdetail, detail } = this.card.getFieldProps(f);
            if (isdetail) {
                if (this.card.cubeForm.has(detail)) {
                    if (!detailObj[detail]) {
                        detailObj[detail] = [];
                    }
                    detailObj[detail].push(field.index);
                }
            }
        });
        if (!_.isEmpty(detailObj)) {
            _.forEach(detailObj, (val, key) => {
                const value:any = _.sortedUniq(val)[0];
                const fieldDetail = this.card.cubeForm.$(key);
                const pageSize = Number(fieldDetail.pageSize);
                const total = fieldDetail.values().length;
                const pageTotal = Math.ceil(total / pageSize);
                for (let i = 1; i <= pageTotal; i++) {
                    if (value >= pageSize * (i - 1) && value < pageSize * i) {
                        fieldDetail.pageNum = i;
                    }
                }
            })
        }
    }
}
